package com.shopping.runbackground.user.service.impl;

import com.shopping.runbackground.user.dao.UserMapper;
import com.shopping.runbackground.user.pojo.Jurisdictionc;
import com.shopping.runbackground.user.pojo.Jurisdictionf;
import com.shopping.runbackground.user.pojo.Sysadmin;
import com.shopping.runbackground.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public Sysadmin login(Sysadmin sysadmin) {
        return userMapper.selectOne(sysadmin);
    }

    @Override
    public List<Sysadmin> findUsers(Sysadmin sysadmin) {
        /*List<Sysadmin> sysadminList = userMapper.select(sysadmin);
        return sysadminList;*/

        Example example=new Example(Sysadmin.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(sysadmin.getUsername())){
            criteria.orLike("username","%"+sysadmin.getUsername()+"%");
        }
        if (StringUtils.isNotEmpty(sysadmin.getName())){
            criteria.orLike("name","%"+sysadmin.getName()+"%");
        }
        if (StringUtils.isNotEmpty(sysadmin.getTel())){
            criteria.orLike("tel","%"+sysadmin.getTel()+"%");
        }
        List<Sysadmin> sysadminList = this.userMapper.selectByExample(example);
        return sysadminList;
    }

    @Override
    public Sysadmin findUserByusername(String username) {
        Sysadmin sysadmin=new Sysadmin();
        sysadmin.setUsername(username);
        sysadmin = userMapper.selectOne(sysadmin);
        List<Jurisdictionf> jurisdictionfList = userMapper.findJurisdictionfByusername(username);
        List<Jurisdictionc> jurisdictioncList = userMapper.findJurisdictioncByusername(username);
        sysadmin.setJurisdictionfList(jurisdictionfList);
        sysadmin.setJurisdictioncList(jurisdictioncList);

        return sysadmin;
    }

    @Override
    public void addUser(Sysadmin sysadmin) {
        userMapper.insertSelective(sysadmin);
        String username = sysadmin.getUsername();
        List<Jurisdictionf> jurisdictionfList = sysadmin.getJurisdictionfList();
        for (Jurisdictionf jurisdictionf : jurisdictionfList) {
            userMapper.addsysadmin_jurisdictionf(jurisdictionf.getJf_id(),username);
        }
        List<Jurisdictionc> jurisdictioncList = sysadmin.getJurisdictioncList();
        for (Jurisdictionc jurisdictionc : jurisdictioncList) {
            userMapper.addUser(jurisdictionc.getJc_id(),username);
        }
    }
}
